 package show.me.the.money.service.core;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import show.me.the.money.accredit.User;
import show.me.the.money.accredit.result.AuthorizeResult;
import show.me.the.money.config.app.Action;
import show.me.the.money.config.app.AppConfigController;
import show.me.the.money.config.app.Module;
import show.me.the.money.util.ConfigValueParser;
import show.me.the.money.util.context.Context;

import java.util.Iterator;


public class ModuleConfigLocator  implements Service{
	private static Log logger = LogFactory.getLog(ModuleConfigLocator.class);
	@SuppressWarnings("unchecked")
	public void execute(HashMap<String,Object> req,HashMap<String,Object> res,Context ctx){
		User user = (User)ctx.get("user.instance");
		String mId = (String)req.get("id");
		int code = 200;
		String msg = "";
		if(StringUtils.isEmpty(mId)){
			logger.error("module id missing");
			code = 401;
			msg = "ModuleIdMissing";
		}
		else{
			Module  m = AppConfigController.instance().findModule(mId);
			if(m == null){
				code = 404;
				msg = "ModuleNotFound";	
			}
			else{
				AuthorizeResult r = user.authorize("apps",m.getFullId());
				if(r.getResult() == AuthorizeResult.NO){
					code = 402;
					msg = "AuthorizeFailed";			
				}
				else{
				
						HashMap<String,Object> body = m.data();
						res.put("body",body);
						
						for(Iterator<String> it = body.keySet().iterator();it.hasNext();){
							String key = it.next();
							Object v = body.get(key);
							if(v instanceof String){
								v = ConfigValueParser.parse((String)v,ctx);
								body.put(key, v);
							}
						}

						List lsActions = new ArrayList();
						body.put("actions", lsActions);
						
						List<Action> ls = m.getAllActions();
						int n = ls.size();
						for(int j = 0; j < n; j ++){
							Action action = ls.get(j);
							r = user.authorize("apps",action.getFullId());
							if(r.getResult() == AuthorizeResult.NO){
								continue;
							}
							lsActions.add(action.data());
						}
						
						code = 200;
						msg = "Success";
							
				}
			}
			
		}
	
		res.put(Service.RES_CODE,code);
		res.put(Service.RES_MESSAGE,msg);	
			
	}
}
